package gui.item;

import gui.common.Controller;
import gui.common.IView;

import java.util.Date;

import model.entity.Item;
import model.management.ItemManager;

import common.Result;

/**
 * Controller class for the edit item view.
 */
public class EditItemController extends Controller implements IEditItemController
{

  private Item target;

  /**
   * Constructor.
   * 
   * @param view
   *          Reference to edit item view
   * @param target
   *          Item that is being edited
   */
  public EditItemController(IView view, ItemData target)
  {
    super(view);

    this.target = target.getTag();

    construct();
  }

  //
  // Controller overrides
  //

  /**
   * Returns a reference to the view for this controller.
   * 
   * {@pre None}
   * 
   * {@post Returns a reference to the view for this controller.}
   */
  @Override
  protected IEditItemView getView()
  {
    return (IEditItemView) super.getView();
  }

  /**
   * Sets the enable/disable state of all components in the controller's view. A component should
   * be enabled only if the user is currently allowed to interact with that component.
   * 
   * {@pre None}
   * 
   * {@post The enable/disable state of all components in the controller's view have been set
   * appropriately.}
   */
  @Override
  protected void enableComponents()
  {
    getView().enableBarcode(false);
    getView().enableDescription(false);
    getView().enableEntryDate(true);
    enableOK();
  }

  /**
   * Loads data into the controller's view.
   * 
   * {@pre None}
   * 
   * {@post The controller has loaded data into its view}
   */
  @Override
  protected void loadValues()
  {
    getView().setBarcode(target.getBarcode().getCode());
    getView().setDescription(target.getProduct().getDescription());
  }

  //
  // IEditItemController overrides
  //

  /**
   * This method is called when any of the fields in the edit item view is changed by the user.
   */
  @Override
  public void valuesChanged()
  {
    enableOK();
  }

  /**
   * This method is called when the user clicks the "OK" button in the edit item view.
   */
  @Override
  public void editItem()
  {
    ItemData data = getNewItemData();

    Result result = ItemManager.validateEditItem(target, data);
    if (result.getStatus())
      ItemManager.editItem(target, data);
  }

  private ItemData getNewItemData()
  {
    Date newDate = getView().getEntryDate();
    ItemData data = new ItemData();
    data.setEntryDate(newDate);

    return data;
  }

  private void enableOK()
  {
    Date date = getView().getEntryDate();
    getView().enableOK(date != null && date.before(new Date()));
  }
}
